//
//  EXTableRootController.m
//  SmallEasyLife
//
//  Created by qianfeng on 15/10/26.
//  Copyright © 2015年 GXK. All rights reserved.
//

#import "EXTableRootController.h"
#import "Masonry.h"
#import "UIImageView+WebCache.h"
#import "Event.h"
#import "UINavigationBar+DynamicTransparency.h"



@interface EXTableRootController ()


@property (nonatomic, strong) NSLayoutConstraint * topGuideConstraint;
@property (nonatomic, strong) NSLayoutConstraint * bottomGuideConstraint;

@property (nonatomic, strong) UIImageView * headImage;


@end

@implementation EXTableRootController
- (void)viewDidLoad {
    [super viewDidLoad];
    
    //push的时候隐藏tabbar
    
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    [self createShareAndCollectBarButton];
    [self createLeftBackButton];
    
    [self tableViewSetup];
}

- (void)createLeftBackButton
{
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [backButton setImage:[UIImage imageNamed:@"back_1"] forState:UIControlStateNormal];
    [backButton setImage:[UIImage imageNamed:@"back_2"] forState:UIControlStateHighlighted];
    backButton.frame = CGRectMake(0, 0, 44, 44);
    
    [backButton addTarget:self action:@selector(backBarButtonTaped:) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem * backBarItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
    self.navigationItem.leftBarButtonItem = backBarItem;
}

- (void)createShareAndCollectBarButton
{
    NSArray<UIBarButtonItem *> * arr = self.navigationItem.rightBarButtonItems;
    
    UIButton * collectButton = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [collectButton setImage:[UIImage imageNamed:@"slike_1"] forState:UIControlStateNormal];
    [collectButton setImage:[UIImage imageNamed:@"slike_2"] forState:UIControlStateSelected];
    
    collectButton.frame = CGRectMake(0, 0, 60, 60);
    [collectButton addTarget:self action:@selector(collectButtonTaped:) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem * collectBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:collectButton];
    UIBarButtonItem * shareBarButtonItem = [arr firstObject];
    NSArray<UIBarButtonItem *> * barButtons = @[shareBarButtonItem, collectBarButtonItem];
    
    self.navigationItem.rightBarButtonItems = barButtons;

}

- (void)collectButtonTaped:(UIButton *)button
{
    button.selected = !button.selected;
    
}
- (void)backBarButtonTaped:(UIButton *)button
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)tableViewSetup
{
//    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.contentInset = UIEdgeInsetsMake(ImageHeight, 0, 0, 0);
    
    [self createTableHeaderView];
}

#pragma scrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat offSetY = scrollView.contentOffset.y;
    UIColor * color = [UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:1.0];
    if (scrollView == self.tableView)
   {
        //控制导航栏的透明度
//        UIColor * color = [UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:1.0];
        NSLog(@"scrollView.contentOffset.y -> %f",scrollView.contentOffset.y);
        
        if (offSetY < -ImageHeight)//下拉放大视图
        {
            CGRect frame = self.headImage.frame;
            frame.origin.y = offSetY;
            frame.size.height =  -offSetY;//contentMode = UIViewContentModeScaleAspectFill时，高度改变宽度也跟着改变
            
            self.headImage.frame = frame;
            
        }
        else if (offSetY >= - ImageHeight && offSetY < -64)//在此阶段是从初始位置（带ImageHeight的偏移量）上拉，应渐变
        {
            CGFloat aph = (ImageHeight + offSetY)/ImageHeight;
            NSLog(@"aph -> %lf",aph);
            [self.navigationController.navigationBar nav_setBackgroundColor:[color colorWithAlphaComponent:aph]];
            
            //控制tableView偏移，让sectionView移动
#warning 待解决问题
            //----------------------------
//            self.tableView.contentInset = UIEdgeInsetsMake(- offSetY, 0, 0, 0);
            
        }
        else if (offSetY >= -64)
        {
#warning 待解决问题
//            self.tableView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0);
            [self.navigationController.navigationBar nav_setBackgroundColor:[color colorWithAlphaComponent:1.0]];
        }
        
   }
    
    else if(scrollView == self.webView.scrollView){
        offSetY -= ImageHeight;
        if (offSetY < -ImageHeight)//下拉放大视图
        {
            NSLog(@"line 140  %lf",self.tableView.contentInset.top);
            self.tableView.contentInset = UIEdgeInsetsMake(- offSetY, 0, 0, 0);
//            self.tableView.frame = CGRectMake(0, 0, self.tableView.frame.size.width, self.tableView.frame.size.height);
            CGRect frame = self.headImage.frame;
            frame.size.height =  -scrollView.contentOffset.y +  ImageHeight;
            self.headImage.frame = frame;
            //contentMode = UIViewContentModeScaleAspectFill时，高度改变宽度也跟着改变
        }
        else if (offSetY >= - ImageHeight && offSetY < 0)//在此阶段是从初始位置（带ImageHeight的偏移量）上拉，应渐变
        {
            NSLog(@"line 149  %lf",self.tableView.contentInset.top);
            CGFloat aph = (ImageHeight + offSetY)/ImageHeight;
            CGRect frame = self.headImage.frame;
            self.headImage.frame = frame;
           self.tableView.contentInset = UIEdgeInsetsMake(- offSetY, 0, 0, 0);
            [self.navigationController.navigationBar nav_setBackgroundColor:[color colorWithAlphaComponent:aph]];
        }else if (offSetY > 0)
        {
            NSLog(@"line157  %lf",self.tableView.contentInset.top);
            CGFloat aph = (ImageHeight + offSetY)/ImageHeight;
            self.tableView.contentInset = UIEdgeInsetsZero;
            [self.navigationController.navigationBar nav_setBackgroundColor:[color colorWithAlphaComponent:aph]];
        }

    }
}

#pragma mark viewController 生命周期函数
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self.navigationController.navigationBar nav_setBackgroundColor:[UIColor clearColor]];
    self.tableView.delegate = self;
    
    //第一次显示的时候手动调用一次
    [self scrollViewDidScroll:self.tableView];
    
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [self.navigationController.navigationBar nav_clear];
    
    self.tableView.delegate = nil;
}

//tableView懒加载
- (UITableView *)tableView
{
    if (nil == _tableView) {
        UITableView * tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
        tableView.backgroundColor = [UIColor redColor];
        [self.view addSubview:tableView];
        
        _tableView = tableView;
        
        //系统的约束布局方法
        self.topGuideConstraint = [NSLayoutConstraint constraintWithItem:self.tableView
                                                               attribute:NSLayoutAttributeTop
                                                               relatedBy:NSLayoutRelationEqual
                                                                  toItem:self.topLayoutGuide
                                                               attribute:NSLayoutAttributeBaseline
                                                              multiplier:1.0
                                                                constant:-64];
        self.bottomGuideConstraint = [NSLayoutConstraint constraintWithItem:self.tableView
                                                                  attribute:NSLayoutAttributeBottom
                                                                  relatedBy:NSLayoutRelationEqual
                                                                     toItem:self.bottomLayoutGuide
                                                                  attribute:NSLayoutAttributeBaseline
                                                                 multiplier:1.0
                                                                   constant:0];
        //约束设定好之后需要加到约束对应的父视图中
        [self.view addConstraints:@[self.topGuideConstraint,self.bottomGuideConstraint]];
        
//        id topLay = self.topLayoutGuide;
        
//        //约束布局
        [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view.mas_left);
            make.right.equalTo(self.view.mas_right);
//            make.height.equalTo(@(self.view.frame.size.height + ImageHeight));
        }];
        [self loadViewIfNeeded];
    }
    return _tableView;
}
//创建头部视图
- (void)createTableHeaderView
{
    UIImageView * headImage = [[UIImageView alloc] init];
    
    headImage.frame = CGRectMake(0, -ImageHeight, self.view.frame.size.width, ImageHeight);
    
    headImage.backgroundColor = [UIColor yellowColor];
    
//    headImage.contentMode = UIViewContentModeScaleAspectFit;
   headImage.contentMode = UIViewContentModeScaleAspectFill;
    
//    headImage.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;

    
    [headImage sd_setImageWithURL:[NSURL URLWithString:[self.model.imgs firstObject]]];
    
    //设置图片适应方式
    
    headImage.clipsToBounds = YES;
    
    self.headImage = headImage;
    
    [self.tableView addSubview:headImage];
    
}

#pragma mark - tableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 100;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
    view.backgroundColor = [UIColor cyanColor];
    return view;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 80;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell * cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    
    cell.textLabel.text = @"asdfasd";
    
    return cell;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
